package com.superhelper.app.interceptor;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.superhelper.common.utils.TimeCostHelper;


/**
 * 日志拦截器
 * 
 * @author duanshao
 * 
 */
public class LogInterceptor extends HandlerInterceptorAdapter {

    private final Logger LOG = LoggerFactory.getLogger("access");

    private final String NEW_LINE = System.getProperty("line.separator", "\n");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Map<String, Object> carrier = new HashMap<String, Object>();
        carrier.put("request", queryString(request));
        carrier.put("uri", request.getRequestURI());
        TimeCostHelper.watch(carrier);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        Map<String, Object> carrier = TimeCostHelper.getCarrier();
        String requestStr = "***";
        if (carrier != null) {
            requestStr = (String) carrier.get("uri");
            requestStr = requestStr + ";" + carrier.get("request");
        }
        LOG.info("cost:{};uri:{};{}request:{}", TimeCostHelper.getTimeCost(), request.getRequestURI(), NEW_LINE,
                requestStr);
        response.setHeader("Access-Control-Allow-Origin", "*");
        TimeCostHelper.clean();
    }

    // FIXME 这个函数会丢掉同名参数吧?
    private String getParams(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        Map<String, String[]> map = request.getParameterMap();
        Set<Entry<String, String[]>> set = map.entrySet();
        Iterator<Entry<String, String[]>> it = set.iterator();
        while (it.hasNext()) {
            Entry<String, String[]> entry = it.next();
            sb.append(entry.getKey() + "=" + entry.getValue()[0]);
            sb.append("&");
        }
        return sb.toString();
    }

    private String queryString(HttpServletRequest request) {
        Map<String, String[]> params = request.getParameterMap();
        String queryString = "";
        Set<String> set = new HashSet<String>(params.keySet());
        for (String key : set) {
            String[] values = params.get(key);
            if (values == null || values.length == 0) {
                continue;
            }
            for (int i = 0; i < values.length; i++) {
                String value = values[i];
                queryString += key + "=" + value + "&";
            }
        }

        String device = request.getHeader("device");
        queryString += "hDvice=" + device;
        String gzVersion = request.getHeader("gzVersion");
        queryString += "&hGzVersion=" + gzVersion;
        String model = request.getHeader("model");
        queryString += "&hModel=" + model;
        String hUserId = request.getHeader("userId");
        queryString += "&hUserId=" + hUserId;
        String deviceAgent = request.getHeader("Device-Agent");
        queryString += "&deviceAgent=" + deviceAgent;
        String token = request.getHeader("token");
        queryString += "&token=" + token;

        return queryString;
    }

}
